# -*-coding:utf-8 -*-
from datetime import datetime, timedelta

from .base import XZBaseHandler


class GPSHandler(XZBaseHandler):
    """更新车辆状态"""
    last_post_time_map = {}

    def handle(self, data):
        """只取最后一条数据,需要大于100s更新一次"""
        vehicle_id = self.map2new_vehicle_id(data['vehicleId'])
        if not vehicle_id:  # 找不到vehicle_id
            return
        last_gps_data = data['appLocations'][-1]

        if vehicle_id not in self.last_post_time_map:
            self.last_post_time_map[vehicle_id] = datetime.now()

        if self.last_post_time_map[vehicle_id] + timedelta(seconds=100) < datetime.now():
            data = {
                "status": "ONLINE",
                "latitude": float(last_gps_data['gpsLat']),
                "longitude": float(last_gps_data['gpsLon']),
                "speed": float(last_gps_data['speed']),
                "last_time": last_gps_data['locationTime']
            }
            self.last_post_time_map[vehicle_id] = datetime.now()
            self.yb_api.update_vehicle_status(vehicle_id, data)
